package com.hua.yuan.ui;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.hua.yuan.base.Constents;
import com.hua.yuan.common.BaseActivity;
import com.hua.yuan.R;
import com.hua.yuan.manager.user.UserManagerModule;
import com.hua.yuan.manager.user.business.IUserBusiness;
import com.hua.yuan.manager.user.business.callback.IUserCallback;
import com.hua.yuan.provider.user.IUserProvider;
import com.hua.yuan.provider.user.User;
import com.hua.yuan.ui.data.LoginDataRequest;
import com.hua.yuan.ui.module.UserInfoBean;
import com.hua.yuan.userlogin.UserLoginModule;
import com.hua.yuan.util.FileUtils;
import com.hua.yuan.util.GlideCircleTransform;
import com.hua.yuan.util.SystemUtils;
import com.hua.yuan.util.ToastUtil;
import com.hua.yuan.util.animation.AnimationListener;
import com.hua.yuan.util.animation.ViewAnimator;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import cm.hua.yuan.common.utils.PreferenceUtils;
import okhttp3.Call;
/**
 * Created by huangyang on 2018/6/23.
 * 显示用户信息的界面
 */

public class UserInfoActivity extends BaseActivity implements View.OnClickListener,IUserCallback<User> {

    private ImageView backImage;
    private TextView titleView;
    private ImageView userImage;
    private RelativeLayout userNickNameRl;
    private TextView userNickName;
    private TextView userPhone;
    private RelativeLayout editPwd;
    private RelativeLayout clickSelectSex;
    private TextView userSex;
    private TextView userYear;
    private TextView userButton;

    private RelativeLayout sexSelectRl;
    private TextView selectBg;
    private LinearLayout selectLl;
    private TextView selectBoy;
    private TextView selectGirl;
    private TextView selectCancel;

    private RelativeLayout yearSelectRl;

    private TimePickerView pvTime;

    private String headUrl = "";

    private IUserProvider mUserProvider;

    private final String TAG=UserInfoActivity.class.getName();


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info);
        mUserProvider=UserLoginModule.getInstance().getProvider();
        initView();
        initData();

    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

    private void initView() {
        backImage = findViewById(R.id.backImage);
        titleView = findViewById(R.id.titleView);
        userImage = findViewById(R.id.userImage);
        userNickName = findViewById(R.id.userNickName);
        userPhone = findViewById(R.id.userPhone);
        editPwd = findViewById(R.id.editPwd);
        clickSelectSex = findViewById(R.id.clickSelectSex);
        userSex = findViewById(R.id.userSex);
        userYear = findViewById(R.id.userYear);
        userButton = findViewById(R.id.userButton);

        sexSelectRl = findViewById(R.id.sexSelectRl);
        selectBg = findViewById(R.id.selectBg);
        selectLl = findViewById(R.id.selectLl);
        selectBoy = findViewById(R.id.selectBoy);
        selectGirl = findViewById(R.id.selectGirl);
        selectCancel = findViewById(R.id.selectCancel);

        yearSelectRl = findViewById(R.id.yearSelectRl);
        userNickNameRl = findViewById(R.id.userNickNameRl);


        backImage.setOnClickListener(this);
        titleView.setText("账户资料");
        editPwd.setOnClickListener(this);
        userImage.setOnClickListener(this);

        clickSelectSex.setOnClickListener(this);
        selectBg.setOnClickListener(this);
        selectBoy.setOnClickListener(this);
        selectGirl.setOnClickListener(this);
        selectCancel.setOnClickListener(this);
        yearSelectRl.setOnClickListener(this);
        userNickNameRl.setOnClickListener(this);
        userButton.setOnClickListener(this);


    }

    private void initData() {

        mUserProvider=UserLoginModule.getInstance().getProvider();
        User user=mUserProvider.getUser();
        if(user==null){
            return;
        }

        String nickName=user.getNickName();
        String mobilePhone=user.getMobilePhone();
        int  sex=user.getSex();
        String headerUrl=user.getHeadUrl();
        String birthday=user.getBirthday();

        if(!TextUtils.isEmpty(nickName)) {

            userNickName.setText(nickName);
        }

        if(!TextUtils.isEmpty(mobilePhone)) {

            userPhone.setText(mobilePhone);
        }

        switch (sex) {

            case 1:
                userSex.setText("男");
                break;
            default:
                userSex.setText("女");
                break;
        }


        if(!TextUtils.isEmpty(birthday)) {
            userYear.setText(birthday);
        }

        if(!TextUtils.isEmpty(headerUrl)) {
            Glide.with(this).load(headUrl)
                    .asBitmap()
                    .transform(new GlideCircleTransform(this))
                    .into(userImage);
        }else {

            Glide.with(this).load(R.drawable.default_img)
                    .asBitmap()
                    .transform(new GlideCircleTransform(this))
                    .into(userImage);
        }
        initTimeSelect();

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.backImage:
                finish();
                break;
            case R.id.editPwd:
                startActivity(new Intent(this, ChangedPwdActivity.class));
                finish();
                break;
            case R.id.userImage:
                //修改头像
//                ImageSelector.builder()
//                        .useCamera(true) // 设置是否使用拍照
//                        .setSingle(true)  //设置是否单选
//                        .start(this, 100); // 打开相册
                break;
            case R.id.userButton:
                //修改信息
                changedUserInfo(true);
                break;

            case R.id.selectBg:
                sexUiShow(false);
                break;
            case R.id.selectBoy:
                userSex.setText("男");
                sexUiShow(false);
                break;
            case R.id.selectGirl:
                userSex.setText("女");
                sexUiShow(false);
                break;
            case R.id.selectCancel:
                sexUiShow(false);
                break;
            case R.id.clickSelectSex:
                sexUiShow(true);
                break;
            case R.id.yearSelectRl:
                showTimeUI();
                break;
            case R.id.userNickNameRl:
                String name = userNickName.getText().toString().trim();
                Intent intent=new Intent(this, ChangeNickActivity.class);
                intent.putExtra("name", name);
                startActivityForResult(intent,UserManagerModule.BUSINESS_NICK_NAME);
                break;

        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == UserManagerModule.BUSINESS_NICK_NAME && data != null) {
            //获取nick_name的值
            String nickName=data.getStringExtra(Constents.USER_NICK_NAME);
            if(TextUtils.isEmpty(nickName)){
                return;
            }
            mUserProvider.getUser().setNickName(nickName);
            userNickName.setText(nickName);
        }
    }


    /**
     * 修改用户的头像
     *
     * @param path   路径
     * @param prefix 后缀
     */
    private void sendImage(String path, String prefix) {

        try {
            String imageStr = FileUtils.imageToBase64(path);
            LoginDataRequest.changedUserHead(imageStr, prefix, new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {

                }

                @Override
                public void onResponse(String response, int id) {

                    try {
                        JSONObject jsonObject = new JSONObject(response);

                        if (!jsonObject.isNull("errno")) {

                            String code = jsonObject.getString("errno");
                            if ("0".equals(code)) {
                                if (!jsonObject.isNull("head_url")) {
                                    String url = jsonObject.getString("head_url");
                                    headUrl = url;
                                    Glide.with(UserInfoActivity.this).load(url)
                                            .asBitmap()
                                            .transform(new GlideCircleTransform(UserInfoActivity.this))
                                            .into(userImage);

                                    //修改用户信息
                                    changedUserInfo(false);

                                }
                            }

                        }


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 显示性别
     *
     * @param flag true显示 false隐藏
     */
    private void sexUiShow(boolean flag) {

        if (flag) {
            //显示
            selectBg.setAlpha(0.0f);
            ViewAnimator.animate(selectBg)
                    .alpha(0.0f, 0.1f, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f, 0.7f, 0.8f, 0.9f, 1.0f)
                    .duration(300)
                    .onStart(new AnimationListener.Start() {
                        @Override
                        public void onStart() {
                            sexSelectRl.setVisibility(View.VISIBLE);
                        }
                    }).start();

            ViewAnimator.animate(selectLl)
                    .translationY(800, 0)
                    .duration(300)
                    .start();


        } else {
            //隐藏
            ViewAnimator.animate(selectBg)
                    .alpha(1.0f, 0.9f, 0.8f, 0.7f, 0.6f, 0.5f, 0.4f, 0.3f, 0.2f, 0.1f, 0.0f)
                    .duration(300)
                    .onStop(new AnimationListener.Stop() {
                        @Override
                        public void onStop() {

                            sexSelectRl.setVisibility(View.GONE);

                        }
                    }).start();

            ViewAnimator.animate(selectLl)
                    .translationY(0, 800)
                    .duration(300)
                    .start();

        }

    }

    /**
     * 初始化时间
     */
    private void initTimeSelect() {
        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        Calendar endDate = Calendar.getInstance();

        //正确设置方式 原因：注意事项有说明
        startDate.set(1970, 0, 1);
        endDate.set(Calendar.getInstance().get(Calendar.YEAR), 11, 31);
        selectedDate.set(2000, 0, 1);


        pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调

                @SuppressLint("SimpleDateFormat")
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                String dateString = formatter.format(date);
                if (userYear != null) {
                    userYear.setText(dateString);
                }

            }
        })
                .setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字
                .setContentTextSize(16)//滚轮文字大小
                .setTitleBgColor(Color.WHITE)
//                .setTitleSize(16)//标题文字大小
                .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
                .setSubCalSize(16)
                .setSubmitColor(Color.parseColor("#333333"))//确定按钮文字颜色
                .setCancelColor(Color.parseColor("#333333"))//取消按钮文字颜色
                .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                .setRangDate(startDate, endDate)//起始终止年月日设定
                .setLabel("年", "月", "日", "", "", "")//默认设置为年月日时分秒
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .isDialog(false)//是否显示为对话框样式
                .setBgColor(Color.WHITE)
//                .setLineSpacingMultiplier(2)
                .setBackgroundId(Color.parseColor("#80000000"))
//                .setTextXOffset(2, 2, 10, 0, 0, 0)
                .build();


    }

    /**
     * 显示时间的UI
     */
    private void showTimeUI() {

        if (pvTime != null) {
            if (pvTime.isShowing()) {
                pvTime.dismiss();
            } else {
                pvTime.show();
            }
        }

    }


    /**
     * 修改用户信息
     *
     * @param flag true提示 false不提示
     */
    private void changedUserInfo(final boolean flag) {

        String mobile = userPhone.getText().toString().trim();
        final String nick_name = userNickName.getText().toString().trim();
        String sex_name = userSex.getText().toString().trim();
        int sex;
        if ("男".equals(sex_name)) {
            sex = 1;
        } else {
            sex = 2;
        }

        final String year = userYear.getText().toString().trim();
        IUserProvider userProvider=UserLoginModule.getInstance().getProvider();
        IUserBusiness userBusiness=UserManagerModule.getInstance().getUserManager();
        if(userBusiness==null || userProvider==null){
            //TODO ZYB 提示更改失败
            ToastUtil.showShortToast( "编辑资料失败");
            return;
        }

        Map userMap=new HashMap<>();
        userMap.put(UserManagerModule.MOBILE,mobile);
        userMap.put(UserManagerModule.NICK_NAME,nick_name);
        userMap.put(UserManagerModule.SEX,sex);
        userMap.put(UserManagerModule.BIRTHDAY,year);
        userMap.put(UserManagerModule.TOKEN,userProvider.getToken());
        userBusiness.updateUserInfo(userMap,userProvider,this);
    }


    @Override
    public void onResult(@NonNull final User pUserInfo) {

        SystemUtils.isMainThread(TAG);
        if(isFinishing()){
            return;
        }

        if(pUserInfo == null){
            ToastUtil.showShortToast( "编辑资料失败");
            return;
        }
        ToastUtil.showShortToast( "编辑资料成功");
        finish();
    }

    @Override
    public void onError(final Throwable e) {
        e.printStackTrace();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ToastUtil.showShortToast( "编辑资料失败");
            }
        });
    }
}
